package com.l024.easysecurity.modules.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.l024.easysecurity.common.utils.GuavaCacheUtil;
import com.l024.easysecurity.common.utils.R;
import com.l024.easysecurity.common.utils.Utils;
import com.l024.easysecurity.modules.sys.entity.SysUser;
import com.l024.easysecurity.modules.sys.service.SysUserService;
import com.l024.easysecurity.modules.sys.shiro.ShiroUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {
    private  final  static Logger logger = LoggerFactory.getLogger(LoginController. class);
    @Autowired
    private Producer producer;
    @Autowired
    private SysUserService sysUserService;

    /**
     * 直接获取验证码图片
     * @param response
     * @throws IOException
     */
    @RequestMapping("captcha.jpg")
    public void getCaptcha(HttpServletResponse response)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }


    /**
     * 前后端分离验证码处理
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("captcha")
    @ResponseBody
    public R captcha(HttpServletResponse response)throws IOException {
        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //生成唯一id
        String uuid = Utils.getUUID();
        //保存到guava
        GuavaCacheUtil.getInstance().getCache().put(uuid,text);
        //BufferedImage转为base64
        String imageBase64 = Utils.BufferedImageToBase64(image);
        Map<String,Object> map = new HashMap<>();
        map.put("tmp",uuid);
        map.put("captcha",imageBase64);
        return R.ok(map);
    }

    /**
     * 登录
     */
    @ResponseBody
    @RequestMapping(value = "/sys/login", method = RequestMethod.POST)
    public R login(@RequestBody JSONObject param) {
        //先判断是否有uuid
        String tmp = param.getString("tmp");
        if(StringUtils.isEmpty(tmp)){
            return R.error("非法请求");
        }
        //从guava中读取出验证码
        String kaptchaCache = GuavaCacheUtil.getInstance().getCache().getIfPresent(tmp);
//        String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
        String captcha = param.getString("captcha");
        if(StringUtils.isEmpty(captcha)){
            return R.error("请输入验证码");
        }
        if(!captcha.equalsIgnoreCase(kaptchaCache)){
            //验证成功后移除验证码
            GuavaCacheUtil.getInstance().getCache().invalidate(tmp);
            return R.error("验证码不正确");
        }
        //验证成功后移除验证码
        GuavaCacheUtil.getInstance().getCache().invalidate(tmp);
        String username = param.getString("username");
        String password = param.getString("password");
        try{
            Subject subject = ShiroUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
        }catch (UnknownAccountException e) {
            return R.error(e.getMessage());
        }catch (IncorrectCredentialsException e) {
            return R.error("账号或密码不正确");
        }catch (LockedAccountException e) {
            return R.error("账号已被锁定,请联系管理员");
        }catch (AuthenticationException e) {
            return R.error("账户不存在");
        }
        //返回用户信息
        SysUser sysUser = sysUserService.findSysUserByUserName(username);
        sysUser.setPassword("");
        return new R().put("msg","登陆成功").put("data",sysUser);
    }

    /**
     * 退出
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public String logout() {
        ShiroUtils.logout();
        return "redirect:login.html";
    }

    @GetMapping("/login")
    @ResponseBody
    public R login(){
        return R.error(401,"请先登录");
    }
//    @GetMapping("/login")
//    public String login(){
//        return "login";
//    }
}
